package cn.rkylin.oms.base.channel.controller;

import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.rkylin.oms.system.project.service.ProjectManagerService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.base.brand.controller.BrandController;
import cn.rkylin.oms.base.brand.domain.Brand;
import cn.rkylin.oms.base.brand.service.IBrandService;
import cn.rkylin.oms.base.brand.vo.BrandVO;
import cn.rkylin.oms.base.channel.dao.ChannelDAOImpl;
import cn.rkylin.oms.base.channel.domain.Channel;
import cn.rkylin.oms.base.channel.service.ChannelServiceImpl;
import cn.rkylin.oms.base.channel.service.IChannelService;
import cn.rkylin.oms.base.channel.vo.ChannelVO;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.system.project.vo.ProjectVO;

/**
 * 渠道Controller
 * 
 * @ClassName ChannelController.java
 * @author Administrator
 * @version V1.0
 * 
 */
@Controller
@RequestMapping("/channel")
public class ChannelController extends ApolloController {

	private static final Log logger = LogFactory.getLog(ChannelController.class);
	private static final String PAGE_SELECT_STATEMENT = "pageSelectChannel";
	private static final String RESULT_SUCCESS_CHANNEL = "success";  
	private static final String RESULT_ERROR_MESSAGE = "errormessage";
	private static final String RESULT_ROW_COUNT = "rowcount";

	@Autowired
	private IChannelService channelService;
	
    /**
     * 项目服务层
     */
    @Autowired
    public ProjectManagerService projectManagerService;

	@Autowired
	private LogUtil logUtil;
	private Object channel;

	/**
	 * 查询渠道列表
	 * 
	 * @param quickSearch
	 *            快速查询条件
	 * @param start
	 *            第几页
	 * @param length
	 *            每页多少行
	 * @return 结果Map
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ResponseBody
	@RequestMapping(value = "/getChannelList")
	public Map<String, Object> getChannelList(String quickSearch,
			@RequestParam(required = false, defaultValue = "0") int start,
			@RequestParam(required = false, defaultValue = "10") int length) {
		Map map = new HashMap();

		try {
			// 处理分页
			if (length == -1) {
				length = Integer.MAX_VALUE;
			}
			int page = start / length + 1;

			ChannelVO param = new ChannelVO();

			// 企业id
			CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
			Map<String, String> enterpriseMap = currentUser.getEnterpriseMap();
			for (Map.Entry<String, String> entry : enterpriseMap.entrySet()) {
				param.setEntId(entry.getKey());
			}

			// 快速查询检索条件
			quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
			if (StringUtils.isNotEmpty(quickSearch)) {
				param.setQuickSearch(quickSearch);
			}

			/*// 处理转义的字段
			Map<String, String> replaceFieldsMap = new HashMap<String, String>();
			replaceFieldsMap.put("enableStatus", "enable");

			// 排序语句生成
			String orderStatement = getOrderString(ChannelDAOImpl.class.getName(), PAGE_SELECT_STATEMENT,
					replaceFieldsMap);
			if (StringUtils.isNotEmpty(orderStatement)) {
				param.setOrderBy(orderStatement);
			}*/

			PageInfo<ChannelVO> channelList = channelService.findByWhere(page, length, param);
			map.put(JSON_RESULT, SUCCESS);
			map.put(RECORDS_FILTERED, channelList.getTotal());
			map.put(RECORDS_TOTAL, channelList.getTotal());
			map.put(RETURN_DATA, channelList.getList());
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			map.put(JSON_RESULT, FAILED);
			map.put(JSON_MSG, ex.getMessage());
		}

		return map;
	}

	/**
	 * 下载渠道
	 * 
	 * @return 结果Map
	 * @throws Exception
	 *             异常
	 */
	@ResponseBody
	@RequestMapping(value = { "/downloadChannel" })
	public Map<String, Object> downloadChannel() throws Exception {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		try {
			String msg = channelService.downloadChannel(1, 0);
//			String msg = channelServiceImpl.downloadChannelNew(1, 0);

			logUtil.info(new DBLog("", "渠道下载", "入渠道信息", "下载成功"));

			if ("".equals(msg)) {
				returnMap.put(JSON_RESULT, SUCCESS);
				returnMap.put(RETURN_DATA, msg);
			} else {
				returnMap.put(JSON_RESULT, FAILED);
				returnMap.put(JSON_MSG, msg);
			}
		} catch (Exception ex) {
			logUtil.info(new DBLog("", "渠道下载", "渠道信息", ex.getMessage()));
			logger.error(ex.getMessage(), ex);
			returnMap.put(JSON_RESULT, FAILED);
			returnMap.put(JSON_MSG, ex.getMessage());
		}

		return returnMap;
	}
	
	/**
	 * 获取渠道明细信息
	 * @param brandId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/channelDetail", method = RequestMethod.GET)
	public Map<String, Object> channelDetail(String channelId) throws Exception {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			ChannelVO channelVO = channelService.getChannelById(channelId);
			if (channelVO != null) {
				returnMap.put(JSON_RESULT, SUCCESS);
				returnMap.put(RETURN_DATA, channelVO);
			} else {
				returnMap.put(JSON_RESULT, FAILED);
				returnMap.put(RESULT_ERROR_MESSAGE, "该渠道不存在");
			}
		} catch (Exception ex) {
			returnMap.put(JSON_RESULT, FAILED);
			returnMap.put(RESULT_ERROR_MESSAGE, ex.getMessage());
		}
		return returnMap;
	}
	
	/**
	 * 创建新渠道
	 * @param channelCode
	 * @param channelName
	 * @param entId
	 * @param remark
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/createChannel")
	public Map<String, Object> createChannel(@RequestBody ChannelVO cVo)
			throws Exception {
		// 用于返回值的json对象
		Map<String, Object> returnMap = new HashMap<String, Object>();
				
		String entId = null;
		// 企业id
		CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
		Map<String, String> enterpriseMap = currentUser.getEnterpriseMap();
		for (Map.Entry<String, String> entry : enterpriseMap.entrySet()) {
			entId=entry.getKey();
		}
		
		ChannelVO channelVO = new ChannelVO();
		channelVO.setChannelCode(cVo.getChannelCode());
		channelVO.setChannelName(cVo.getChannelName());
		channelVO.setEntId(entId);
		channelVO.setProject(cVo.getProject());
		channelVO.setProjectCode(cVo.getProjectCode());
		channelVO.setUpdateTime(new Date());
		channelVO.setCreateTime(new Date());
		channelVO.setChannelId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
		channelVO.setRemark(cVo.getRemark());

		// 判断编码是否存在
		Channel channel = channelService.getChannelByChannelCode(channelVO);
		if(channel!=null) {
			returnMap.put(RESULT_ERROR_MESSAGE,"该渠道编码已存在");
			returnMap.put(RESULT_SUCCESS_CHANNEL,"n");
			return returnMap;
		}

		// 判断该数据是否启用
		channelService.insert(channelVO);
		returnMap.put(RESULT_ROW_COUNT,1);
		returnMap.put(RESULT_SUCCESS_CHANNEL,"Y");
		// 生成返回结果json串，null内容也需要返回
		return returnMap;
	}

	/**
	 * 修改渠道信息
	 * @param channelID
	 * @param channelCode
	 * @param channelName
	 * @param project
	 * @param remark
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/updateChannel")
	public Map<String, Object> updateChannel(@RequestBody ChannelVO cVo) throws Exception {
		// 用于返回值的json对象
		Map<String, Object> returnMap = new HashMap<String, Object>();

		ChannelVO channelVO = channelService.getChannelById(cVo.getChannelId());
		channelVO.setChannelCode(cVo.getChannelCode());
		channelVO.setChannelName(cVo.getChannelName());
		channelVO.setProjectCode(cVo.getProjectCode());
		channelVO.setProject(cVo.getProject());
		channelVO.setRemark(cVo.getRemark());
		channelVO.setUpdateTime(new Date());

		//判断编码是否存在
		Channel channel = channelService.getChannelByChannelCode(channelVO);
		if(channel!=null) {
			returnMap.put(RESULT_SUCCESS_CHANNEL, "n");
			returnMap.put(RESULT_ERROR_MESSAGE, "该渠道编码已存在");
			return returnMap;
		}

		//判断该数据是否启用
		channelService.update(channelVO);
		returnMap.put(RESULT_ROW_COUNT,1);
		returnMap.put(RESULT_SUCCESS_CHANNEL,"Y");
		// 生成返回结果json串，null内容也需要返回
		return returnMap;
	}

	/**
	 * 删除渠道
	 * @param channel
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteChannel")
	public Map<String, Object> deleteChannel(String channelId)
			throws Exception {
		// 用于返回值的json对象
		Map<String, Object> returnMap = new HashMap<String, Object>();

		//分担规则生成
		int result =  channelService.delete(channelId);
		returnMap.put(RESULT_ROW_COUNT,result);
		returnMap.put(RESULT_SUCCESS_CHANNEL,"Y");
		// 生成返回结果json串，null内容也需要返回
		return returnMap;
	}   

}
